<template>
  <el-row>
    <el-cascader
        v-model="identifier"
        :options="dataEvent"
        @change="eventChange"
        style="width: 100%"
    />
  </el-row>
  <el-row>
    <code-editor ref="editor" v-model="code" :json="true" theme="nord"/>
  </el-row>
  <el-row>
    <el-button type="primary" @click="sendCommand">发送指令</el-button>
    <el-button @click="prettyCode">格式化数据</el-button>
    <el-button @click="resetEvent">重置数据</el-button>
  </el-row>
</template>

<script>
import {validatejson, validatenull} from "@/utils/validate";

export default {
  name: "simulatorEvent",
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      code: '',
      event: {},
      identifier: '',
      dataEvent: [],
    };
  },
  watch: {
    modelValue() {
      if (validatenull(this.modelValue)) {
        return;
      }
      this.loadEvent();
    }
  },
  methods: {
    loadEvent() {
      this.dataEvent = this.modelValue.blocks.map(block => ({
        value: block.id,
        label: block.blockName,
        children: this.modelValue.events.filter(event => event.blockId === block.id).map(item => {
          return {
            value: item.identifier,
            label: `${item.name} - ${item.identifier}`,
          }
        })
      }));
    },
    eventChange(value) {
      if (validatenull(value) || value.length === 0) {
        return;
      }
      this.identifier = value[1];
      this.event = this.modelValue.events.find(item => item.identifier === this.identifier);
    },
    sendCommand() {
      if (validatenull(this.identifier)) {
        this.$message.warning('请先选择事件');
        return;
      }
      if (validatenull(this.code)) {
        this.$message.warning('请填写调试数据');
        return;
      }
      if (!validatejson(this.code)) {
        this.$message.warning('Json格式不正确');
        return;
      }
      const output = JSON.stringify(JSON.parse(this.code)); // 尝试解析并重新编码 JSON
      const data = {
        eventName: this.event.name,
        eventType: this.event.eventType,
        output: output
      };
      this.$emit('sendCommand', data, this.identifier);
    },
    prettyCode() {
      this.$refs.editor.prettyCode();
    },
    resetEvent() {
      this.code = '';
    },
  }
}
</script>
